<!--
  _______
 |__   __|
    | |  ___  _ __ __      __ ___  _ __
    | | / _ \| '__|\ \ /\ / // _ \| '__|
    | ||  __/| |    \ V  V /|  __/| |
    |_| \___||_|     \_/\_/  \___||_|
-->
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" th:with="id=${post?.postId},title='写文章,更新文章'">
<head th:include="include/edit_inc::commonHeaderCustom('',~{::style})">
    <style type="text/css">
        pre {
            padding: 10px 15px;
            margin: 10px 0;
        }

        pre code {
            font-size: 12px;
            font-family: Courier New;
        }
    </style>
</head>

<body>
<!-- 头部开始 -->
<!-- hilightjs -->
<link rel="stylesheet" type="text/css" href="https://apps.bdimg.com/libs/highlight.js/9.1.0/styles/github.min.css">
<link rel="dns-prefetch" href="//cdn.mathjax.org"/>
<link rel="stylesheet" type="text/css" href="https://static-rs-terwer.oss-cn-beijing.aliyuncs.com/lib/simplemde/simplemde.min.css"/>
<!--<link rel="stylesheet" type="text/css" href="http://www.layui.com/admin/std/dist/layuiadmin/style/admin.css"/>-->
<header th:include="include/edit_inc::commonHeaderContent">
</header>

<div class="content">
    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-card-header">写文章</div>
            <div class="layui-card-body" style="padding: 15px;">
                <form class="layui-form" action="" method="post" lay-filter="component-form-group"
                      onsubmit="return false;">
                    <div class="layui-form-item">
                        <label class="layui-form-label">文章标题</label>
                        <div class="layui-input-block">
                            <input type="text" name="postTitle" th:value="${post?.postTitle}" lay-verify="postTitle" autocomplete="off" placeholder="请输入标题" class="layui-input" th:disabled="${post.postType!=null && post.postType eq 'essay'}">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">标题别名</label>
                        <div class="layui-input-block">
                            <input type="text" name="postSlug" th:value="${post?.postSlug}" lay-verify="postSlug" autocomplete="off" placeholder="标题别名" class="layui-input" th:disabled="${post.postType!=null && post.postType eq 'essay'}">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">文章类型</label>
                        <div class="layui-input-block">
                            <select name="postType" lay-filter="post-type-change">
                                <option value="post" th:selected="${post.postType==null || post.postType eq 'post'}">文章</option>
                                <option value="note" th:selected="${post.postType!=null && post.postType eq 'note'}">笔记</option>
                                <option value="essay" th:selected="${post.postType!=null && post.postType eq 'essay'}">随笔</option>
                                <option value="page" th:selected="${post.postType!=null && post.postType eq 'page'}">页面</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">文章状态</label>
                        <div class="layui-input-block">
                            <select name="postStatus">
                                <option value="publish" selected th:selected="${post.postStatus==null || post.postStatus eq 'publish'}">已发布
                                </option>
                                <option value="draft" th:selected="${post.postStatus!=null && post.postStatus eq 'draft'}">草稿
                                </option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-form-item layui-form-text">
                        <label class="layui-form-label">文章内容</label>
                        <div class="layui-input-block">
                            <textarea id="content" name="content" th:utext="${post?.postRawContent}" placeholder="请输入内容" class="layui-textarea"></textarea>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">发布日期</label>
                        <div class="layui-input-block">
                            <input type="text" id="postDdate" name="postDate" th:value="${post?.postDate==null?(#dates.format(#dates.createNow(), 'yyyy-MM-dd HH:mm:ss')):(#dates.format(post.postDate, 'yyyy-MM-dd HH:mm:ss'))}" lay-verify="datetime" placeholder="yyyy-MM-dd HH:mm:ss" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item layui-layout-admin">
                        <div class="layui-input-block">
                            <div class="layui-footer" style="left: 0;z-index: 999999;">
                                <button class="layui-btn" lay-submit="" lay-filter="post-form-submit">立即提交</button>
                                <button type="reset" class="layui-btn layui-btn-danger">重置</button>
                                <button class="layui-btn layui-btn-primary" id="screenButton">全屏</button>
                                <a th:if="${postId>0}" href="javascript:void(0);" th:onclick="'window.open(BLOG_BASE_URL+' + '\'post/' + ${postId} + '.html\');'">
                                    <button class="layui-btn layui-btn-normal" style="margin-left: 10px;" id="preview">预览</button>
                                </a>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 底部开始 -->
<script type="text/javascript" src="https://static-rs-terwer.oss-cn-beijing.aliyuncs.com/lib/simplemde/simplemde.min.js"></script>
<!-- hilightjs -->
<script type="text/javascript" src="http://apps.bdimg.com/libs/highlight.js/9.1.0/highlight.min.js"></script>
<!-- mathjax -->
<script src="//cdn.bootcss.com/mathjax/2.7.4/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<footer th:include="include/edit_inc::commonFooterCustom(~{::script})">
    <script type="text/javascript" th:inline="javascript">
        var simplemde = null;

        $(document).ready(function () {
            fullscreen("screenButton");

            $("#preview").on("click", function () {
                var url = $(this).parent().attr("href");
                top.window.location.href = url;
            });
        });

        $(function () {
            MathJax.Hub.Config({
                tex2jax: {
                    inlineMath: [
                        ["$", "$"], ["\(", "\)"]
                    ]
                }
            });

            var QUEUE = MathJax.Hub.queue;
            simplemde = new SimpleMDE({
                element: document.getElementById("content"),
                placeholder: "请输入文章内容...",
                spellChecker: false,
                previewRender: function (plainText) {
                    var preview = document.getElementsByClassName("editor-preview-side")[0];
                    preview.innerHTML = this.parent.markdown(plainText);
                    preview.setAttribute('id', 'editor-preview')
                    MathJax.Hub.Queue(["Typeset", MathJax.Hub, "editor-preview"]);
                    return preview.innerHTML;
                },
                renderingConfig: {
                    codeSyntaxHighlighting: true,
                },
            });
            // simplemde.toggleSideBySide()//打开实时全屏预览
        });

        /**
         * 子iframe全屏
         *
         *@param objId 点击按钮的ID
         */
        function fullscreen(objId) {
            // 判断是否允许全屏
            var fullscreenEnabled =
                document.fullscreenEnabled ||
                document.mozFullScreenEnabled ||
                document.webkitFullscreenEnabled ||
                document.msFullscreenEnabled;

            // 全屏
            function launchFullscreen(element) {
                if (element.requestFullscreen) {
                    element.requestFullscreen();
                } else if (element.mozRequestFullScreen) {
                    element.mozRequestFullScreen();
                } else if (element.msRequestFullscreen) {
                    element.msRequestFullscreen();
                } else if (element.webkitRequestFullscreen) {
                    element.webkitRequestFullScreen();
                }
            }

            // 退出全屏
            function exitFullscreen() {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.msExitFullscreen) {
                    document.msExitFullscreen();
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen();
                } else if (document.webkitExitFullscreen) {
                    document.webkitExitFullscreen();
                }
            }

            var btn = document.querySelector('#' + objId);
            if (fullscreenEnabled) {
                btn.addEventListener('click', function () {
                    var fullscreenElement =
                        document.fullscreenElement ||
                        document.mozFullScreenElement ||
                        document.webkitFullscreenElement;
                    if (fullscreenElement) {
                        exitFullscreen();
                        btn.innerHTML = '全屏';
                    } else {
                        launchFullscreen(document.documentElement);
                        btn.innerHTML = '退出全屏';
                    }
                }, false);
            }
            // 监听全屏事件
            document.addEventListener('webkitfullscreenchange', function fullscreenChange() {
                if (document.fullscreenEnabled ||
                    document.webkitIsFullScreen ||
                    document.mozFullScreen ||
                    document.msFullscreenElement) {
                    console.log('enter fullscreen');
                } else {
                    console.log('exit fullscreen');
                }
            }, false);
        }

        layui.config({base: BUGUCMS_BASE_URL + 'static/lib/'}).extend({
            conf: 'bugucms/conf',
            tips: 'bugucms/extend/tips'
        }).use(['conf', 'tips', 'form', 'layer', 'laydate'], function () {
            var conf = layui.conf,
                laydate = layui.laydate,
                form = layui.form;

            laydate.render({
                elem: '#postDdate',
                type: 'datetime'
            });

            /* 监听提交 */
            form.on('submit(post-form-submit)', function (data) {
                var content = simplemde.value();
                if (data.field.postType == 'post' && data.field.postTitle == '') {
                    top.layer.msg('文章标题不能为空', {icon: 2});
                    return false;
                }
                if (data.field.postType == 'page' && data.field.postTitle == '') {
                    top.layer.msg('页面标题不能为空', {icon: 2});
                    return false;
                }
                if (content == "") {
                    top.layer.msg('内容不能为空', {icon: 2});
                    return false;
                } else {
                    data.field.content = content;
                }
                console.log('最终的提交信息:' + JSON.stringify(data.field))
                //提交数据到服务器
                var postId = /*[[${postId}]]*/'0';
                console.log('postId:' + postId);
                if (postId > 0) {//修改文章
                    console.log("修改文章");
                    var editPostUrl = BLOG_API_BASE_URL + "post/update";
                    // 如果开启token，传入token
                    if (conf.request.tokenName) {
                        editPostUrl += '?tokenString=' + conf.request.tokenString;
                    }
                    $.post(editPostUrl, {
                        postId: postId,
                        postType: data.field.postType,
                        postStatus: data.field.postStatus,
                        postTitle: data.field.postTitle,
                        postSlug: data.field.postSlug,
                        postContent: data.field.content,
                        postDate: data.field.postDate
                    }, function (res) {
                        console.log(JSON.stringify(res));
                        if (res.status == 1) {
                            layer.msg('修改成功', {icon: 1});
                            window.location.reload();
                        } else {
                            layer.msg('修改失败', {icon: 2});
                        }
                    });
                } else {//写文章
                    console.log("写文章");
                    var newPostUrl = BLOG_API_BASE_URL + "post/new";
                    // 如果开启token，传入token
                    if (conf.request.tokenName) {
                        newPostUrl += '?tokenString=' + conf.request.tokenString;
                    }
                    $.post(newPostUrl, {
                        postType: data.field.postType,
                        postStatus: data.field.postStatus,
                        postTitle: data.field.postTitle,
                        postSlug: data.field.postSlug,
                        postContent: data.field.content,
                        postDate: data.field.postDate
                    }, function (res) {
                        var postId = JSON.stringify(res.data.postId);
                        console.log("postId:" + postId);
                        if (postId > 0) {
                            layer.msg('发布成功', {icon: 1});
                            top.window.location.href = BUGUCMS_BASE_URL + BUGUCMS_ADMIN_PATH + "/?action=blog/postManage/list&title=所有文章"
                        } else {
                            layer.msg('发布失败', {icon: 2});
                        }
                    });
                }
                return false;
            });

            form.on('select(post-type-change)', function (data) {
                console.log(data.value);
                var postType = data.value;
                if (postType == 'essay') {
                    $('input[name="postTitle"]').attr("disabled", true);
                    $('input[name="postSlug"]').attr("disabled", true);
                } else {
                    $('input[name="postTitle"]').attr("disabled", false);
                    $('input[name="postSlug"]').attr("disabled", false);
                }
            });
        });
    </script>
</footer>
</body>
